package map.android.baidu.carpool.page.usercenter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.widget.MToast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.DriverCommentListData;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.adpater.EvaluteDriverAdapter;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.response.DriverCommentListResponse;
import map.android.baidu.carpool.response.DriverCommentListResponse.DriverCommentItem;
import map.android.baidu.carpool.response.MainConfigResponse;
import map.android.baidu.carpool.response.OrderDetailResponse;
import map.android.baidu.carpool.utils.LogUtils;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.widget.RoundImageView;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshBase;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;

/**
 * @Author chenlei18
 * @Description 车主评价
 * @CreateTime 2015-3-27 下午3:48:50
 */
public class EvaluateDriverPage extends CarpoolBasePage implements View.OnClickListener {

    private Context mContext;
    private LayoutInflater mInflater;
    private Resources mRes;

    private View mView;
    private TitleHelpler mTitleHelper;

    private TextView mDriverNameTv;
    private TextView mDriverInfoTv;
    private TextView mEvaluateNumTv;
    private TextView mEvaluateNumTvHead;
    private RatingBar mRatingBar;
    private PullToRefreshListView mPtrlv;
    private ListView mListView;
    private EvaluteDriverAdapter mAdapter;
    private RoundImageView mDriverHeadIm;
    private int mEvaluateConut;
    private ArrayList<DriverCommentItem> mCommentList;

    private ImageLoader mImageLoader;
    private DisplayImageOptions options;

    private static int mPn = 0;
    private static int mDeltaPn;

    private Bundle mBundle;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = APIProxy.res().getBaseActivity();
        mInflater = APIProxy.res().getInflater();
        mRes =  APIProxy.res().getResources();
        if (mView == null) {
            mView = APIProxy.res().inflate(R.layout.carpool_evalute_driver_page);
            mBundle = getArguments();
            mPn = 0;
            initView();
            initImageLoader();
            initData();
            requestEvaluateData();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }
        return mView;
    }

    OrderDetailResponse mResponse;
    private void initData() {
        if(mBundle != null){
            if(mBundle.containsKey(OrderDetailResponse.class.getName())){
                mResponse = (OrderDetailResponse) mBundle.get(OrderDetailResponse.class.getName());
                if(mResponse != null && mResponse.data != null) {
                    if(!TextUtils.isEmpty(mResponse.data.carerNickname)) {
                        mDriverNameTv.setText(mResponse.data.carerNickname);
                    }
                        StringBuilder sb = new StringBuilder();
                    if(!TextUtils.isEmpty(mResponse.data.carColor)){
                        sb.append(mResponse.data.carColor + " ");
                    }
                    if(!TextUtils.isEmpty(mResponse.data.carBrand)){
                        sb.append(mResponse.data.carBrand + " ");
                    }
                    if(!TextUtils.isEmpty(mResponse.data.carNumber)){
                        sb.append(mResponse.data.carNumber + " ");
                    }
                    if(!TextUtils.isEmpty(mResponse.data.carType)){
                        String carTypeValue = "";
                        MainConfigResponse mainConfigResponse = CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity());
                        if(mainConfigResponse != null && mainConfigResponse.data != null && mainConfigResponse.data.carType != null && mainConfigResponse.data.carType.size() != 0){
                            for(int index = 0; index < mainConfigResponse.data.carType.size(); index++){
                                if(mainConfigResponse.data.carType.get(index) != null){
                                    if(mResponse.data.carType.equals(mainConfigResponse.data.carType.get(index).type)){
                                        carTypeValue = mainConfigResponse.data.carType.get(index).name;
                                    }
                                }
                            }
                        }
                        if(!TextUtils.isEmpty(carTypeValue)) {
                            sb.append("(" + carTypeValue + ")");
                        }
                    }
                    displayImageView(mResponse.data.carerPic, mDriverHeadIm);
                    mDriverInfoTv.setText(sb.toString());
                    mRatingBar.setRating(mResponse.data.carerStar);
                    mRatingBar.setIsIndicator(true);
                }
            }
        }
    }

    private void initView() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mBundle.putBoolean("needRefresh", false);
                goBack(mBundle);
            }
        });
        mTitleHelper.setCenterView("车主评价");
        mDriverHeadIm = (RoundImageView) mView.findViewById(R.id.car_driver_circle_image);
        mDriverNameTv = (TextView) mView.findViewById(R.id.driver_name);
        mDriverInfoTv = (TextView) mView.findViewById(R.id.driver_info);
        mEvaluateNumTv = (TextView) mView.findViewById(R.id.user_evaluate_num);
        mRatingBar = (RatingBar) mView.findViewById(R.id.car_driver_ratingbar);
        mPtrlv = (PullToRefreshListView) mView.findViewById(R.id.evaluate_driver_listview);
        mPtrlv.setMode(Mode.DISABLED);

        mPtrlv.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                mDeltaPn = 1;
                turnPage(mDeltaPn);
            }
        });

        FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        mListView = mPtrlv.getRefreshableView();
        mListView.setLayoutParams(params1);
        mListView.setBackgroundColor(0xededed);
        mListView.setVerticalScrollBarEnabled(false);
        mListView.setDividerHeight(0);
        mListView.setHeaderDividersEnabled(false);
        mListView.setFooterDividersEnabled(false);
        mListView.setCacheColorHint(0x00000000);
        mListView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mListView.setFadingEdgeLength(0);

        mAdapter = new EvaluteDriverAdapter();
        addHeadView();
        mListView.setAdapter(mAdapter);
    }

    public void turnPage(int deltaNum) {
        mPn = mPn + deltaNum;
        requestEvaluateData();
    }

    /**
     * add head view to listview
     */
    private void addHeadView() {
        View headView = APIProxy.res().inflate(R.layout.evaluate_driver_listview_head);
        mEvaluateNumTvHead = (TextView) headView.findViewById(R.id.user_evaluate_num);
        mListView.addHeaderView(headView, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 
     */
    private void requestEvaluateData() {
        if (!checkNetworkStatus(true)) {
            return;
        }
        showLoadingDialog(true);
        DriverCommentListData mDriverCommentListData;
        IDataStatusChangedListener<DriverCommentListResponse> listener = new IDataStatusChangedListener<DriverCommentListResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<DriverCommentListResponse> data, DriverCommentListResponse response, int dataStatus) {
                showLoadingDialog(false);
                if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                    if (response != null && response.data != null) {
                        setUserCount(response.data.count);
                        if (response.data != null && response.data.commentList != null && response.data.commentList.size() > 0) {
                            mCommentList = response.data.commentList;
                            mAdapter.addData(mCommentList);
                            mAdapter.notifyDataSetChanged();
                            updatePageAndUi(response);
                        }
                    } else {
                        mPn = mPn - mDeltaPn;
                        MToast.show(mContext, "网络连接异常，请检查网络");
                        showLoadingDialog(false);
                    }
                } else {
                    mPn = mPn - mDeltaPn;
                    showLoadingDialog(false);
                    MToast.show(mContext, "网络连接异常，请检查网络");
                }
            }
        };
        //  参数没有传递
        mDriverCommentListData = new DriverCommentListData(mActivity);
        if(mResponse != null && mResponse.data != null){
            mDriverCommentListData.setCarerId(mResponse.data.carerId);
        }
        mDriverCommentListData.setPn(mPn);
        mDriverCommentListData.setRn(10);
        mDriverCommentListData.post(listener);
    }


    /**
     * 更新页面页码和list是否可翻页
     */
    private void updatePageAndUi(DriverCommentListResponse response) {
        if (response == null) {
            return;
        }
        int totalPages = 0;
        double pagesDou = (double)response.data.count / 10;
        totalPages = (int)Math.ceil(pagesDou);
        LogUtils.d("zty", "当前页面+==" + mPn + "**" + totalPages);
        mPtrlv.onRefreshComplete();
        if (0 == mPn) {
            if (totalPages <= 1) {
                mPtrlv.setMode(Mode.DISABLED);
            } else {
                mPtrlv.setMode(Mode.PULL_UP_TO_REFRESH);
            }
        } else if (mPn == (totalPages - 1)) {
            mPtrlv.setMode(Mode.DISABLED);
        } else {
            mPtrlv.setMode(Mode.PULL_UP_TO_REFRESH);
        }
    }

    /**
     * @param count
     */
    protected void setUserCount(int count) {
        StringBuilder sb = new StringBuilder();
        sb.append("来自");
        sb.append("<font color=\"#ff481d\">");
        sb.append(count);
        sb.append("</font>");
        sb.append("人");
        CharSequence cs = Html.fromHtml(sb.toString());
        mEvaluateNumTv.setText(cs);
        mEvaluateNumTvHead.setText(cs);
    }


    private void initImageLoader() {
        mImageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .cacheInMemory()
                .cacheOnDisc()
                .showImageForEmptyUri(APIProxy.res().getDrawable(R.drawable.car_driver_bg))
                .cacheInMemory().build();
    }

    private void displayImageView(String url, ImageView imageView) {
        String finalUrl = "";
        finalUrl = url;
        mImageLoader.clearDiskCache();
        mImageLoader.displayImage(finalUrl, imageView, options, new SimpleImageLoadingListener());

    }
}
